using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Phoenix;
using Phoenix.Commands;
using Phoenix.Framework;

namespace HelloWorld.ViewModels.Home
{
    public class MenuViewModel : ViewModelBase
    {
        public MenuViewModel(ObservableCollection<MenuItem> menuItems)
        {
            MenuItems = menuItems;
            BackCommand = new DelegateCommand(NavigateBack, CanNavigateBack);
            MenuItemSelectedCommand = new DelegateCommand<MenuItem>(ItemSelected);
        }

        void ItemSelected(MenuItem obj)
        {
            if (obj.IsLeaf)
                InvokeActionBuilder.InvokeAction(Context.ResolveFrame("ContentView"), 
                    ControllerAction.CreateFrom(obj.ControllerAction));
            else
                InvokeActionBuilder.InvokeAction(ControllerAction.CreateFrom("Main.Menu"), new object[]{obj});
        }

        bool CanNavigateBack()
        {
            return MenuItems.Any(m => m.Parent != null);
        }

        public ICommand BackCommand { get; private set; }

        public ObservableCollection<MenuItem> MenuItems { get; private set; }

        public ICommand MenuItemSelectedCommand { get; private set; }
    }
}